<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/6/3
 * Time: 10:46
 */

namespace app\index\controller;


use app\common\constants\DBConstant;
use app\common\exception\CustomerException;
use app\common\library\DDingUtil;
use app\common\model\House;
use app\common\util\CommonUtil;
use think\facade\Cache;

/**
 * 销售带看房
 * Class Entrust
 * @package app\index\controller
 */
class SellerAppointment extends Base
{

    public function initialize()
    {
        parent::initialize();
        if (session("web_user")['type'] != 2) throw new CustomerException("只有销售人员才能访问");
    }

    /**
     * 带看记录
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function index()
    {
        $requestData = $this->request->only(["page", "limit", "start_time", "end_time"]);
        return (new \app\common\model\SellerAppointment())->findByUserId(session("web_user")['id'], empty($requestData['start_time']) ? null : $requestData['start_time'], empty($requestData['end_time']) ? null : $requestData['end_time'], $requestData['page'], $requestData['limit']);
    }

    /**
     * 预约看房
     * @throws CustomerException
     */
    public function appointment()
    {
        $requestData = $this->request->only(['username', 'phone', 'remark', 'house_id']);
        $houseInfo = (new House())->findById($requestData['house_id']);
        $requestData['user_id'] = session("web_user")['id'];
        $requestData['amount'] = $houseInfo['amount'];
        $requestData['status'] = 2;
        $validate = new \app\common\validate\SellerAppointment();
        $checkFlag = $validate->scene("add")->check($requestData);
        if (!$checkFlag) throw new CustomerException($validate->getError());
        $flag = (new \app\common\model\SellerAppointment())->save($requestData);
        if (!$flag) throw new CustomerException("预约失败,请稍后重试");
        return "预约成功";
    }

    /**
     * 带看提交完成
     * @return string
     * @throws CustomerException
     */
    public function complete()
    {
        $requestData = $this->request->only(['id', 'remark', 'photos']);
        $webUser = session("web_user");
        $model = new \app\common\model\SellerAppointment();
        $findData = $model->findById($requestData['id']);
        if ($findData['user_id'] != $webUser['id'] || $findData['status'] !== 2) throw new CustomerException("无效的带看信息");
        $findData['remark'] = $requestData['remark'];
        $findData['photos'] = explode(",", $requestData['photos']);
//        $findData['photos'] = $requestData['photos'];
        $validate = new \app\common\validate\SellerAppointment();
        $checkFlag = $validate->scene("update")->check($findData);
        if (!$checkFlag) throw new CustomerException($validate->getError());
        $findData['photos'] = CommonUtil::joinString($findData['photos'], DBConstant::TABLE_FIELD_JOIN_SYMBOL);
        $findData['status'] = 3;
        $flag = $model->where("id", $requestData['id'])->update($findData->toArray());
        if (!$flag) throw new CustomerException("提交失败,请稍后重试");
        Cache::rm("seller_appointment:" . $requestData["id"]);
        return "提交成功";
    }

    /**
     * 带看详情
     * @return array|mixed|null|\PDOStatement|string|\think\Model
     * @throws CustomerException
     */
    public function detail()
    {
        $id = $this->request->get("id");
        if (empty($id)) throw new CustomerException("缺少参数id");
        $findData = (new \app\common\model\SellerAppointment())->selectById($id);
        $webUser = session("web_user");
        if (empty($findData) || $webUser['id'] != $findData["user_id"]) throw new CustomerException("未找到指定的带看信息");
        $houseModel = new House();
        $findData['house'] = $houseModel->selectById($findData['house_id'], true);
        return $findData;
    }

    /**
     * 得到看房密码
     * @return mixed
     * @throws CustomerException
     */
    public function getHousePassword()
    {
        $user = session("web_user");
        $id = $this->request->get("id");
        if (empty($id)) throw new CustomerException("缺少参数id");
        $data = model("seller_appointment")->findById($id);
        if ($data["user_id"] != $user['id']) throw new CustomerException("未找到相关的数据信息");
        $houseData = $data["house"];
        if (empty($houseData["uuid"])) throw new CustomerException("该房源缺少参数uuid,请联系管理员处理");
        $passwordId = empty($data["password_id"]) ? 3001 : $data["password_id"];
        $phone = empty($user["phone"]) ? "17774974894" : $user["phone"];

        $hour = date("H");
        if ($hour < 9 || $hour > 18) {
            throw new CustomerException("该时间段不允许获取密码，请联系管理员");
        }
        $passwordData = DDingUtil::getHousePassword($houseData['house_no'], $houseData['uuid'], $phone, $passwordId);
        $updateData = [
            "house_password" => $passwordData['password'],
            "password_expire_time" => $passwordData["invalid_time"],
            "password_id" => $passwordData["id"],
            "code" => $passwordData["code"],
        ];
        (new \app\common\model\SellerAppointment())->where("id", $id)->update($updateData);
        Cache::rm("seller_appointment:" . $id);
        return $updateData;
    }

}